import 'package:flutter/material.dart';

class TextView extends StatefulWidget {
  final String? data;

  /// 默认显示1行
  final int? maxLines;
  final EdgeInsets? margin;
  final EdgeInsets? padding;
  final AlignmentGeometry? alignment;
  final Color? backcolor;
  final void Function()? onclick;
  final double? width;
  final double? height;

  /// 渐变
  final Gradient? gradient;

  /// 边框颜色
  final Color? borderColor;

  /// 边框宽度
  final double? borderWidth;

  /// 是否使用上级的约束,默认不使用
  final bool useConstrained;

  /// 是否要切圆角,设置时，需要设置颜色
  //final double? radius;
  final BorderRadiusGeometry? radius;

  /// 默认省略
  final TextOverflow? overflow;

  /// 将逻辑像素改成1.0，不根据手机分辨率进行变化
  final double? textScaleFactor;
  final TextStyle? style;
  final TextAlign? textAlign;

  /// 文本显示方向
  final TextDirection? textDirection;

  const TextView(this.data,
      {Key? key,
      this.maxLines = null,
      this.overflow = TextOverflow.ellipsis,
      this.textScaleFactor = 1.0,
      this.style,
      this.textAlign,
      this.textDirection,
      this.margin,
      this.padding,
      this.backcolor,
      this.radius,
      this.onclick,
      this.gradient,
      this.borderColor,
      this.borderWidth,
      this.useConstrained = true,
      this.width,
      this.height,
      this.alignment})
      : super(key: key);

  @override
  State<TextView> createState() => _TextViewState();
}

class _TextViewState extends State<TextView> {
  @override
  Widget build(BuildContext context) {
    // 边框
    BoxBorder? borderWidget;
    if (widget.borderWidth != null && widget.borderColor != null) {
      borderWidget =
          Border.all(width: widget.borderWidth!, color: widget.borderColor!);
    }
    // 装饰
    Decoration? decorationWidget;
    if (widget.radius != null) {
      decorationWidget = BoxDecoration(
          color: (widget.gradient != null) ? null : widget.backcolor,
          // 渐变和颜色不能同时使用
          gradient: widget.gradient,
          borderRadius: widget.radius,
          border: borderWidget);
    }
    Widget contentWidget = Container(
      alignment: widget.alignment,
      color: (widget.radius != null) ? null : widget.backcolor,
      width: widget.width,
      height: widget.height,
      margin: widget.margin,
      padding: widget.padding,
      constraints: const BoxConstraints(minWidth: 23),
      decoration: decorationWidget,
      child: Text(
        widget.data ?? "",
        maxLines: widget.maxLines,
        overflow: widget.overflow,
        textScaleFactor: widget.textScaleFactor,
        style: widget.style,
        textAlign: widget.textAlign,
        textDirection: widget.textDirection,
      ),
    );

    // 是否使用上级的约束,默认不使用
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: widget.onclick,
      child: (widget.useConstrained == true)
          ? contentWidget
          : UnconstrainedBox(child: contentWidget),
    );
  }
}
